/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ivanbiz.service;

import com.ivanbiz.dao.BankDAO;
import com.ivanbiz.dao.GLAccountDAO;
import com.ivanbiz.dao.InvoiceDAO;
import com.ivanbiz.dao.KelasDAO;
import com.ivanbiz.dao.impl.BankDAOImpl;
import com.ivanbiz.dao.impl.GLAccountDAOImpl;
import com.ivanbiz.dao.impl.InvoiceDAOImpl;
import com.ivanbiz.dao.impl.KelasDAOImpl;
import com.ivanbiz.model.Bank;
import com.ivanbiz.model.GLAccount;
import com.ivanbiz.model.Invoice;
import com.ivanbiz.model.Kelas;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

/**
 *
 * @author IW20149X
 */
public class TagihanActionService extends SelectorComposer<Component> {

    String nii;
    Invoice invoice;
    InvoiceDAO invoiceDAO;
    KelasDAO kelasDAO;
    BankDAO bankDAO;
    GLAccountDAO gLAccountDAO;
    @Wire
    Window winTagihanAction;
    @Wire
    Datebox date;
    @Wire
    Textbox NII;
    @Wire
    Combobox listKelas;
    @Wire
    Combobox listBank;
    @Wire
    Combobox listKepada;
    @Wire
    Textbox jumlahPeserta;
    @Wire
    Textbox untukPembayaran;
    @Wire
    Combobox listDitrafer;
    @Wire
    Textbox detailKepada;
    @Wire
    Textbox detailDitranfer;
    @Wire
    Textbox terbilang;
    @Wire
    Textbox jumlahTagihan;
    @Wire
    Textbox jatuhTempo;

    @Override
    public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp);
        invoiceDAO = new InvoiceDAOImpl();
        kelasDAO = new KelasDAOImpl();
        bankDAO = new BankDAOImpl();
        gLAccountDAO = new GLAccountDAOImpl();
        loadKelas();
        loadDitransfer();
        invoice = (Invoice) Executions.getCurrent().getArg().get("invoice");
        if (invoice != null) {
            nii = invoice.getNII();
            renderBank(invoice.getKelas().getTransactionReference());
            renderKepada(invoice.getBank());
            String[] kepada = invoice.getDeskripsiKepada().split("#");
            listKepada.setValue(kepada[1] + " A/C No. " + kepada[0]);
            Map mapKepada = new HashMap();
            mapKepada.put("nameGL", kepada[1]);
            mapKepada.put("noGL", kepada[0]);
            GLAccount gLAccount = (GLAccount) gLAccountDAO.getDataByEqualMore(GLAccount.class, mapKepada);
            detailKepada.setValue(gLAccount.getDeskripsi());
            jumlahTagihan.setValue(String.valueOf(new Double(invoice.getJumlahTagihan()).intValue()));
            terbilang(jumlahTagihan.getValue());
            String[] ditransferKe = invoice.getDeskripsiUntuk().split("#");
            listDitrafer.setValue(ditransferKe[1] + " A/C No. " + ditransferKe[0]);
            Map mapDitransferKe = new HashMap();
            mapDitransferKe.put("nameGL", ditransferKe[1]);
            mapDitransferKe.put("noGL", ditransferKe[0]);
            GLAccount gLAccounts = (GLAccount) gLAccountDAO.getDataByEqualMore(GLAccount.class, mapDitransferKe);
            detailDitranfer.setValue(gLAccounts.getDeskripsi());
        }
    }

    private void loadKelas() {
        try {
            listKelas.getItems().clear();
            List<Kelas> loadKelas = kelasDAO.getDataByEquals(Kelas.class, "statusKelas", "N");
            for (Kelas kelas : loadKelas) {
                Comboitem item = new Comboitem();
                item.setValue(kelas);
                item.setLabel(kelas.getTransactionReference());
                listKelas.appendChild(item);
            }
        } catch (Exception ex) {
            Logger.getLogger(TagihanActionService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Listen("onSelect=#listKelas;")
    public void pilihKelas() {
        try {
            listBank.getItems().clear();
            Kelas kelas = listKelas.getSelectedItem().getValue();
            List<Bank> loadBank = bankDAO.getDataBankByKelas(kelas.getTransactionReference());
            for (Bank bank : loadBank) {
                Comboitem item = new Comboitem();
                item.setValue(bank);
                item.setLabel(bank.getNama());
                listBank.appendChild(item);
            }
        } catch (Exception ex) {
            Logger.getLogger(TagihanActionService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Listen("onSelect=#listBank;")
    public void pilihBank() {
        renderKepada();
        renderJumlahPeserta();
    }

    private void renderKepada() {
        try {
            listKepada.getItems().clear();
            Bank bank = listBank.getSelectedItem().getValue();
            Map map = new HashMap();
            map.put("nama", bank.getNama());
            map.put("groupACC", "Debitur");
            List<GLAccount> loadGLAccounts = gLAccountDAO.getDataByEqualsMore(GLAccount.class, map);
            for (GLAccount gLAccount : loadGLAccounts) {
                Comboitem item = new Comboitem();
                item.setValue(gLAccount);
                item.setLabel(gLAccount.getNameGL() + " A/C No. " + gLAccount.getNoGL());
                listKepada.appendChild(item);
            }
        } catch (Exception ex) {
            Logger.getLogger(TagihanActionService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void renderJumlahPeserta() {
        try {
            Kelas kelas = listKelas.getSelectedItem().getValue();
            Bank bank = listBank.getSelectedItem().getValue();
            String peserta = kelasDAO.getDataPeserta(kelas, bank);
            jumlahPeserta.setValue(peserta);
        } catch (Exception ex) {
            Logger.getLogger(TagihanActionService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Listen("onSelect=#listKepada;")
    public void pilihKepada() {
        GLAccount gLAccount = listKepada.getSelectedItem().getValue();
        detailKepada.setValue(gLAccount.getDeskripsi());
    }

    private void loadDitransfer() {
        try {
            listDitrafer.getItems().clear();
            List<GLAccount> loadGLAccountsKreditur = gLAccountDAO.getDataByEquals(GLAccount.class, "groupACC", "Kreditur");
            for (GLAccount gLAccount : loadGLAccountsKreditur) {
                Comboitem item = new Comboitem();
                item.setValue(gLAccount);
                item.setLabel(gLAccount.getNameGL() + " A/C No. " + gLAccount.getNoGL());
                listDitrafer.appendChild(item);
            }
        } catch (Exception ex) {
            Logger.getLogger(TagihanActionService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Listen("onSelect=#listDitrafer;")
    public void pilihDitransferKe() {
        GLAccount gLAccount = listDitrafer.getSelectedItem().getValue();
        detailDitranfer.setValue(gLAccount.getDeskripsi());
    }

    @Listen("onChange=#jumlahTagihan;")
    public void pilihJumlahTagihan() {
        terbilang(jumlahTagihan.getValue());
    }

    private void terbilang(String jumlahTagihans) {
        if (jumlahTagihan.getValue().isEmpty()) {
            terbilang.setValue("");
        } else {
            try {
                Long.parseLong(jumlahTagihan.getValue());
                terbilang.setText(ServiceHelper.bilang(Long.parseLong(jumlahTagihan.getValue())) + " rupiah");
            } catch (Exception e) {
                Messagebox.show("Format salah, harus angka");
            }
        }
    }

    @Listen("onClick=#simpan;")
    public void simpan() {
        if (invoice == null) {
            invoice = new Invoice();
        }
        invoice.setDate(date.getValue());
        invoice.setNII(NII.getValue());
        invoice.setKelas((Kelas) (listKelas.getSelectedItem() == null ? null : listKelas.getSelectedItem().getValue()));
        invoice.setBank((Bank) (listBank.getSelectedItem() == null ? null : listBank.getSelectedItem().getValue()));
        GLAccount gLAccountKepada = listKepada.getSelectedItem().getValue();
        invoice.setDeskripsiKepada(listKepada.getSelectedItem() == null ? null : gLAccountKepada.getNoGL() + "#" + gLAccountKepada.getNameGL() + "#" + gLAccountKepada.getKode());
        invoice.setDeskripsiUntukPembayaran(untukPembayaran.getValue());
        invoice.setDeskripsiJumlahPeserta(jumlahPeserta.getValue());
        invoice.setJumlahTagihan(jumlahTagihan.getValue().isEmpty() ? (double) 0 : new Double(jumlahTagihan.getValue()));
        invoice.setStatus("0");
        invoice.setJatuhTempo(jatuhTempo.getValue());
        GLAccount gLAccountUntuk = listDitrafer.getSelectedItem().getValue();
        invoice.setDeskripsiUntuk(listDitrafer.getSelectedItem() == null ? null : gLAccountUntuk.getNoGL() + "#" + gLAccountUntuk.getNameGL());
        validate(invoice);
    }

    private void validate(Invoice invoice) {
        if (invoice.getDate() == null) {
            Messagebox.show("Date tidak boleh kosong");
        } else if (invoice.getNII().trim().isEmpty()) {
            Messagebox.show("No Tagihan / Invoice tidak boleh kosong");
        } else if (invoice.getKelas().getTransactionReference().trim().isEmpty()) {
            Messagebox.show("Kelas tidak boleh kosong");
        } else if (invoice.getBank().getNama().trim().isEmpty()) {
            Messagebox.show("Bank tidak boleh kosong");
        } else if (invoice.getDeskripsiJumlahPeserta().trim().isEmpty()) {
            Messagebox.show("Jumlah Peserta tidak boleh kosong");
        } else if (invoice.getDeskripsiKepada().equals("##null")) {
            Messagebox.show("Kepada tidak boleh kosong");
        } else if (invoice.getDeskripsiUntukPembayaran().trim().isEmpty()) {
            Messagebox.show("Untuk Pembayaran tidak boleh kosong");
        } else if (invoice.getJumlahTagihan() == ((double) 0)) {
            Messagebox.show("Jumlah Tagihan tidak boleh kosong");
        } else if (invoice.getJatuhTempo().trim().isEmpty()) {
            Messagebox.show("Jatuh Tempo tidak boleh kosong");
        } else if (invoice.getDeskripsiUntuk().equals("#null")) {
            Messagebox.show("Mohon Ditranfer ke tidak boleh kosong");
        } else {
            long a = invoice.getId();
            if (a == 0) {
                try {
                    if (invoiceDAO.validateField(Invoice.class, "NII", NII.getValue()).equals("Data sudah ada")) {
                        Messagebox.show("No Tagihan / NII sudah ada");
                    } else {
                        invoiceDAO.saveOrUpdate(invoice);
                        winTagihanAction.detach();
                    }
                } catch (Exception ex) {
                    Logger.getLogger(TagihanActionService.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                if (!nii.equals(NII.getValue())) {
                    try {
                        if (invoiceDAO.validateField(Invoice.class, "NII", NII.getValue()).equals("Data sudah ada")) {
                            Messagebox.show("No Tagihan / NII sudah ada");
                        } else {
                            invoiceDAO.saveOrUpdate(invoice);
                            winTagihanAction.detach();
                        }
                    } catch (Exception ex) {
                        Logger.getLogger(TagihanActionService.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else {
                    try {
                        invoiceDAO.saveOrUpdate(invoice);
                        winTagihanAction.detach();
                    } catch (Exception ex) {
                        Logger.getLogger(TagihanActionService.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }

    private void renderKepada(Bank bank) {
        try {
            listKepada.getItems().clear();
            Map map = new HashMap();
            map.put("nama", bank.getNama());
            map.put("groupACC", "Debitur");
            List<GLAccount> loadGLAccounts = gLAccountDAO.getDataByEqualsMore(GLAccount.class, map);
            for (GLAccount gLAccount : loadGLAccounts) {
                Comboitem item = new Comboitem();
                item.setValue(gLAccount);
                item.setLabel(gLAccount.getNameGL() + " A/C No. " + gLAccount.getNoGL());
                listKepada.appendChild(item);
            }
        } catch (Exception ex) {
            Logger.getLogger(TagihanActionService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void renderBank(String transactionReference) {
        try {
            listBank.getItems().clear();
            List<Bank> loadBank = bankDAO.getDataBankByKelas(transactionReference);
            loadBank.add(0, invoice.getBank());
            for (Bank bank : loadBank) {
                Comboitem item = new Comboitem();
                item.setValue(bank);
                item.setLabel(bank.getNama());
                listBank.appendChild(item);
            }
        } catch (Exception ex) {
            Logger.getLogger(TagihanActionService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
